package pers.kw.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.servlet.HandlerInterceptor;
import pers.kw.entity.TokenDto;
import pers.kw.protocol.TokenContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后续改为若依中的拦截器 HeaderInterceptor
 */
@Slf4j
public class TokenInfoInterceptor implements HandlerInterceptor {

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String authorization = request.getHeader("Authorization");
        authorization = StringUtils.removeStartIgnoreCase(authorization, "bearer ");
        if (StringUtils.isNotBlank(authorization) &&
                !authorization.equalsIgnoreCase("null") &&
                !authorization.equalsIgnoreCase("undefined")) {
            Jwt decode = JwtHelper.decode(authorization);
            String claims = decode.getClaims();
            JSONObject jsonObject = JSONObject.parseObject(claims);
            jsonObject.remove("user_name");
            TokenDto token = JSONObject.parseObject(jsonObject.toJSONString(), TokenDto.class);
            TokenContext.setToken(token);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) {
        TokenContext.remove();
    }
}
